#!/usr/bin/env bash
# Copyright (c) 2024 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -e
pwd # out/target_name
root_path=`pwd`
echo "root_path=$root_path"
openvpn_path="$root_path/openvpn"
lzo_path="$root_path/lzo"
openssl_path="$root_path/openssl"
selected_platform="linux-armv4"

openvpn_out_obj_path=${root_path}/${selected_platform}

# delete the old output files
rm -rf ${openvpn_out_obj_path}

# touch an empty openvpn file for syntax check by build.gn 
mkdir -p ${openvpn_out_obj_path}/sbin
touch ${openvpn_out_obj_path}/sbin/openvpn
chmod 777 ${openvpn_out_obj_path}/sbin/openvpn

# 1. build lzo
pushd ${lzo_path}
    ./configure \
    --prefix=${openvpn_out_obj_path} \
    --enable-static \
    --target=arm-linux-gnueabi \
    --host=arm-linux-gnueabi
    make clean && make && make install -j24 >/dev/null 2>&1
popd

# 2. build openssl
pushd ${openssl_path}
    ./Configure gcc \
    -static \
    -no-shared \
    --prefix=${openvpn_out_obj_path} \
    --cross-compile-prefix=arm-linux-gnueabi-
    make clean && make && make install -j24 >/dev/null 2>&1
popd

# 3. build openvpn
pushd ${openvpn_path}
    ./configure \
    --target=arm-linux-gnueabi \
    --host=arm-linux-gnueabi \
    --prefix=${openvpn_out_obj_path} \
    --disable-server \
    --enable-static \
    --disable-shared \
    --disable-debug \
    --disable-plugins \
    OPENSSL_LIBS="-L${openvpn_out_obj_path}/lib -lssl -lcrypto" \
    OPENSSL_CFLAGS="-I${openvpn_out_obj_path}/include" \
    LZO_CFLAGS="-I${openvpn_out_obj_path}/include" \
    LZO_LIBS="-L${openvpn_out_obj_path}/lib -llzo2"
    sed -i 's/\/usr\/sbin\/ifconfig/\/system\/bin\/ifconfig/g' config.h
    make clean && make LIBS="-all-static" && make install -j24 >/dev/null 2>&1
popd
